package cn.edu.suda.catalina.dataupdate.util;

import java.io.*;

/**
 * Created by admin on 2017/5/17.
 */
public class ClassLoaderUtil extends ClassLoader {
    private String filePath;

    ClassLoaderUtil(String filePath) {
        this.filePath = filePath;
    }

    /**
     * 动态加载class文件
     * @param name 包名.类名
     * @return
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name) {
        String className = ClassNameUtil.getClassName(name);
        File classFile = new File(filePath, className);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len = 0;
        try {
            InputStream inputStream = new FileInputStream(classFile);
            while ((len = inputStream.read(b)) != -1) {
                byteArrayOutputStream.write(b, 0, len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return byteArrayOutputStream.toByteArray();
    }
}
